<template>
  <div>
    <h2>{{editMode?"编辑":"创建"}}影片</h2>
    <el-form ref="form" :model="movieForm" label-width="80px">

      <el-form-item label="影片Id" v-if="!editMode">
        <el-input v-model="movieForm.movieId"></el-input>
      </el-form-item>

      <el-form-item label="影片名称">
        <el-input v-model="movieForm.name"></el-input>
      </el-form-item>

      <el-form-item label="英文名称">
        <el-input v-model="movieForm.nameEn"></el-input>
      </el-form-item>

      <el-form-item label="影片海报">
        <el-upload class="avatar-uploader"
                   action="/api/movies/admin/upload"
                   :headers="uploadHeaders"
                   name="imageFile"
                   :on-success="uploadSuccess"
                   :show-file-list="false">
          <img v-if="imageUrl!=''" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item label="影片类型">
        <el-checkbox-group v-model="selectedTypes">
          <el-checkbox v-for="typeItem in typeList" :key="typeItem.typeId" :label="typeItem.name" name="movieType"></el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="综合评分">
        <el-rate v-model="movieForm.rating" :max="10" :allow-half="true" :show-score="true"></el-rate>
      </el-form-item>

      <el-form-item label="参演人数">
        <el-input v-model="movieForm.personCount"></el-input>
      </el-form-item>


      <el-form-item label="上映日期">
        <el-date-picker v-model="movieForm.moviePublishDate"
                        type="date" placeholder="选择日期"
                        format="yyyyMMdd"
                        value-format="yyyyMMdd"
        >
        </el-date-picker>
      </el-form-item>


      <el-form-item label="影片导演">
        <el-select v-model="selectedDirector"
                   value-key="directorId"
                   :filterable="true"
                   :remote="true"
                   :remote-method="loadDirectors"
                   placeholder="请选择活动区域">
          <el-option v-for="director in directorList" :key="director.directorId"
                     :label="director.name" :value="director"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="影片剧情">
        <el-input type="textarea" rows="5" v-model="movieForm.story"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="doPublish">立即创建</el-button>
        <el-button @click="goBack">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      typeList: [], //分类候选项
      directorList: [], //导演候选项
      selectedTypes: [], //已选择分类
      selectedDirector: null, //已选择导演

      imageUrl: "", //当前已选海报图片
      uploadHeaders:{},

      editMode:false,//是否编辑模式
      editMovieId:0,//编辑的影片id
      movieForm: {
        movieId: 0,
        name: "",
        nameEn: "",
        img: "",
        rating: 0.0,
        directorInfo: {},
        personCount: 0,
        story: "",
        moviePublishDate: "",
        movieYear: 0,
        typeInfoList: []
      }
    }
  },
  methods:{
    loadTypeList(){
      this.$http({
        url:'/api/movies/categories'
      }).then((response)=>{
        console.log("获取影片类型数据：",response);
        if(response.status==200){
          if(response.data){
            this.typeList=response.data;
          }
        }
      })
    },
    loadDirectors(keyword){
      console.log("导演关键字搜索：",keyword);
      this.$http({
        url:'/api/movies/directors',
        params:{keyword:keyword},
      }).then((response)=>{
        console.log("获取影片导演数据：",response);
        if(response.status==200){
          if(response.data){
            this.directorList=response.data;
          }
        }
      })
    },
    doPublish(){
      //导演
      this.movieForm.directorInfo=this.selectedDirector;
      //年份
      if(this.movieForm.moviePublishDate!=null && this.movieForm.moviePublishDate.length>0){
        this.movieForm.movieYear=this.movieForm.moviePublishDate.substring(0,4);
      }

      //重新组装的目标数组
      let typeArry=[];
      for(let i=0;i<this.selectedTypes.length;i++){
        let typeItem=this.typeList.find((item)=>{
          if(item.name==this.selectedTypes[i]){
            return item;
          }
        });
        typeArry.push(typeItem);
      }
      this.movieForm.typeInfoList=typeArry;
      if(this.imageUrl.length>0){
        this.movieForm.img=this.imageUrl;
        this.movieForm.bigImage=this.imageUrl;
      }
      console.log("待提交的影片数据:",this.movieForm);
      //对movieForm进行校验
      if(this.movieForm.movieId==0){
        this.$message.warning("请填写影片Id");
        return;
      }
      if(this.movieForm.name==""){
        this.$message.warning("请输入影片名称");
        return;
      }
      if(this.movieForm.img==null || this.movieForm.img==""){
        this.$message.warning("请上传影片海报");
        return;
      }
      if(this.movieForm.typeInfoList==null || this.movieForm.typeInfoList.length==0){
        this.$message.warning("请选择影片分类");
        return;
      }
      if(this.movieForm.personCount==0 ){
        this.$message.warning("请输入参演人数");
        return;
      }
      if(this.movieForm.directorInfo==null ){
        this.$message.warning("请选择影片导演");
        return;
      }

      let url="",method="POST";
      //如果是新增模式
      if(!this.editMode){
        url='/api/movies/admin/create';
      }else{
        url='/api/movies/admin/update'
        method="PUT"
      }
      //发送数据到API
      this.$http({
        url:url,
        method:method,
        data:this.movieForm
      }).then((response)=>{
        console.log("影片数据保存响应：",response);
        if(response.status==200){
          this.$message.success("保存成功");
          this.$router.back();
        }
      })
    },
    uploadSuccess(response, file, fileList){
      console.log("上传成功回调:",response,file,fileList);
      this.imageUrl=response;
    },
    loadEditMovieItem(){
      //调用影片详情api
      this.$http({
        url:'/api/movies/detail/'+this.editMovieId,
        method:'GET'
      }).then((response)=>{
        console.log("需要编辑的影片详情：",response);
        if(response.status==200){
          this.movieForm=response.data;
          //回写影片id
          this.movieForm.movieId=this.editMovieId;
          //回写导演信息，因为导演信息可能不在前20个导演列表中，所以用此导演姓名进行查询一次。
          this.selectedDirector=this.movieForm.directorInfo;
          this.loadDirectors(this.selectedDirector.name);
          let typesArr=this.movieForm.typeInfoList;
          for(let i=0;i<typesArr.length;i++){
            this.selectedTypes.push(typesArr[i].name);
          }

          //回写影片海报
          this.imageUrl=this.movieForm.img;
        }
      })
    },
    goBack(){
      this.$router.back();
    }
  },
  mounted() {
    //无论新增/修改模式都需要运行这三步
    this.loadTypeList();
    this.loadDirectors();
    this.uploadHeaders={
      'Authorization':localStorage.getItem("usertoken")
    }

    //解析路由参数
    let queryParams=this.$route.query;
    console.log("获得查询参数：",queryParams);
    if(queryParams && queryParams.isEdit){
      this.editMode=true;
      this.editMovieId=queryParams.movieId;
    }
    //如果是编辑模式，加载影片信息并赋值给movieForm
    if(this.editMode){
      this.loadEditMovieItem();
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
